package com.tianji.learning.mq;


import cn.hutool.core.util.ObjectUtil;
import com.tianji.api.dto.trade.OrderBasicDTO;
import com.tianji.common.utils.CollUtils;
import com.tianji.learning.service.ILearningLessonService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import static com.tianji.common.constants.MqConstants.Exchange.ORDER_EXCHANGE;
import static com.tianji.common.constants.MqConstants.Key.ORDER_PAY_KEY;
import static com.tianji.common.constants.MqConstants.Key.ORDER_REFUND_KEY;

@Slf4j
@Component
@RequiredArgsConstructor
public class LessonChangeListener {
    private final ILearningLessonService learningLessonService;
    /**
     * 01 监听订单支付 -> 添加课程信息 （day02 -- 随堂练习 01）
     * @param orderBasicDTO
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "learn.lesson.pay.queue",durable = "true")   ,
            exchange = @Exchange(name = ORDER_EXCHANGE,type = ExchangeTypes.TOPIC),
            key = ORDER_PAY_KEY
    ))
    public void listenLessonPay(OrderBasicDTO orderBasicDTO) {
        //1 健壮性处理
        //如果 orderBasicDTO为空，或userId为空，或courseIds为空，记录错误  直接返回
        if (ObjectUtil.isEmpty(orderBasicDTO)|| ObjectUtil.isEmpty(orderBasicDTO.getUserId())|| ObjectUtil.isEmpty(orderBasicDTO.getCourseIds())){
            //数据有问题，无需要处理
            log.error("订单支付后课程消息有误，无法添加到课表中");
            return;
        }
        //2 添加课程到课表
        log.info("监听到用户{}的订单，添加课程{}到课表中",orderBasicDTO.getUserId(),orderBasicDTO.getCourseIds());
        learningLessonService.addLessons(orderBasicDTO.getUserId(),orderBasicDTO.getCourseIds());
    }

    /**
     * 02 监听取消订单消息 -> 删除课程 （ day02 - 作业 - 04）
     * @param order
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "learning.lesson.refund.queue", durable = "true"),
            exchange = @Exchange(name = ORDER_EXCHANGE, type = ExchangeTypes.TOPIC),
            key = ORDER_REFUND_KEY
    ))
    public void listenLessonRefund(OrderBasicDTO order){
        // 1.健壮性处理
        if(order == null || order.getUserId() == null || CollUtils.isEmpty(order.getCourseIds())){
            // 数据有误，无需处理
            log.error("接收到MQ消息有误，订单数据为空");
            return;
        }
        // 2.添加课程
        log.debug("监听到用户{}的订单{}要退款，需要删除课程{}", order.getUserId(), order.getOrderId(), order.getCourseIds());
        learningLessonService.deleteCourseFromLesson(order.getUserId(), order.getCourseIds().get(0));
    }


}
